﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO;
using DeepForest.Phone.Assets.Tools;
using unifiqAnthony.GeocodeService;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
using Microsoft.Phone.Tasks;
using System.Text;

namespace unifiqAnthony
{
    public partial class ListingUpdate : PhoneApplicationPage
    {
        internal const string id = "Aggp0yd8miqzaqQrXChtjs8v2m4nlHd3lFn06-W9gu7ZI4KBhTzUddWbVjayXfTV"; //Bing key
        UnifiqSvc.Listing listing = null;
        List<byte[]> byteList = null;

        int uid;

        PhotoChooserTask photoChooserTask;
        int photoSelected = 0;

        public ListingUpdate()
        {
            InitializeComponent();

            var obj = App.Current as App;
            uid = obj.uid;

            photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);

            byteList = new List<byte[]>();
            byteList.Add(null);
            byteList.Add(null);
            byteList.Add(null);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // Populate Fields
            loadData();
        }

        void loadData()
        {
            var obj = App.Current as App;

            // Load Photos
            byteList = obj.byteList;

            int insCount = 1;
            foreach (byte[] x in byteList)
            {
                System.Diagnostics.Debug.WriteLine(x == null);

                if (x != null)
                {
                    Image img;
                    if (insCount == 1)
                    {
                        img = image1;
                        insCount++;
                    }
                    else if (insCount == 2)
                    {
                        img = image2;
                        insCount++;
                    }
                    else
                    {
                        img = image3;
                    }

                    BitmapImage bmp = new BitmapImage();
                    bmp.SetSource(new MemoryStream(x));

                    //bmp.SetSource(ms);
                    img.Source = bmp;
                }
            }

            // Get Listing from obj
            listing = obj.listing;
            UnifiqSvc.Listing l = obj.listing;
            this.listing = l;

            string msg = "";
            if (NavigationContext.QueryString.TryGetValue("msg", out msg))
                textBlock1.Text = msg;
            int uid;

            uid = l.uid;
            tb_stName.Text = l.stName;
            tb_stNo.Text = l.stNo;
            tb_blkNo.Text = l.blkNo;
            tb_doorNo.Text = l.doorNo;
            tb_apptNo.Text = l.apptNo;
            tb_zipCode.Text = l.zipCode;
            tb_bldngName.Text = l.bldngName;
            tb_contactNo.Text = l.contactNo;
            tb_desc.Text = l.description;
            tb_fullName.Text = l.contactName;
            tb_noOfTenants.Text = l.noOfTenants.ToString();
            tb_fee.Text = l.fee.ToString();
        }


        void prepareData()
        {
            listing.stName = tb_stName.Text;
            listing.stNo = tb_stNo.Text;
            listing.blkNo = tb_blkNo.Text;
            listing.doorNo = tb_doorNo.Text;
            listing.apptNo = tb_apptNo.Text;
            listing.zipCode = tb_zipCode.Text;
            listing.bldngName = tb_bldngName.Text;
            listing.contactNo = tb_contactNo.Text;
            listing.description = tb_desc.Text;
            listing.contactName = tb_fullName.Text;
            listing.noOfTenants = Int32.Parse(tb_noOfTenants.Text);
            listing.fee = Double.Parse(tb_fee.Text);

            // Store bytes to Listing obj
            int count = 1;
            foreach (byte[] x in byteList)
            {
                if (x != null)
                {
                    if (count == 1)
                    {
                        listing.img1 = x;
                    }
                    else if (count == 2)
                    {
                        listing.img2 = x;
                    }
                    else if (count == 3)
                    {
                        listing.img3 = x;
                    }
                    count++;
                }
            }

            var obj = App.Current as App;
            obj.byteList = byteList;
            obj.listing = listing;

        }

        private void btn_next_Click(object sender, RoutedEventArgs e)
        {
            bool valid = true;
            StringBuilder builder = new StringBuilder();

            if (tb_stName.Text == "")
            {
                builder.Append("* Street Name is required \n");
                valid = false;
            }
            if (tb_stNo.Text == "")
            {
                //builder.Append("* Street No. is required \n");
                //valid = false;
            }
            if (tb_blkNo.Text == "")
            {
                builder.Append("* Blk No. is required \n");
                valid = false;
            }
            if (tb_doorNo.Text == "")
            {
                builder.Append("* Door No. is required \n");
                valid = false;
            }
            if (tb_apptNo.Text == "")
            {
                builder.Append("* Street No. is required \n");
                valid = false;
            }
            if (tb_zipCode.Text == "")
            {
                builder.Append("* Zip Code is required \n");
                valid = false;
            }
            //tb_bldngName.Text;
            if (tb_contactNo.Text == "")
            {
                builder.Append("* Contact No. is required \n");
                valid = false;
            }
            else if (tb_contactNo.Text.Length < 8)
            {
                builder.Append("* Enter a local 8 digit phone number \n");
                valid = false;
            }
            //tb_bldngName.Text;
            if (tb_fullName.Text == "")
            {
                builder.Append("* Name is required \n");
                valid = false;
            }
            //tb_desc.Text;
            if (tb_noOfTenants.Text == "")
            {
                builder.Append("* Max No. of Tenants is required \n");
                valid = false;
            }
            if (tb_fee.Text == "")
            {
                builder.Append("* Monthly Fee is required \n");
                valid = false;
            }

            //valid = true; // TEST DATA

            if (valid == false)
            {
                NotificationTool.Show(
                "Missing / Invalid Fields",
                builder.ToString(),
                new NotificationAction("OK", () => { }));
            }
            else
            {
                prepareData();
                NavigationService.Navigate(new Uri("/ListingUpdateConfirm.xaml", UriKind.Relative));
            }


        }

        void previewImage(int pos)
        {
            NavigationService.Navigate(new Uri("/ImagePreview.xaml?pos=" + pos, UriKind.Relative));
        }

        private void btn_image1_Click(object sender, RoutedEventArgs e)
        {
            photoChooserTask.ShowCamera = true;
            photoChooserTask.Show();
            photoSelected = 1;
        }

        private void btn_image2_Click(object sender, RoutedEventArgs e)
        {
            photoChooserTask.ShowCamera = true;
            photoChooserTask.Show();
            photoSelected = 2;
        }

        private void btn_image3_Click(object sender, RoutedEventArgs e)
        {
            photoChooserTask.ShowCamera = true;
            photoChooserTask.Show();
            photoSelected = 3;
        }
        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {

                //Code to display the photo on the page in an image control named myImage.
                BitmapImage bmp = new BitmapImage();

                if (photoSelected == 1)
                {
                    byteList[0] = ChosenPhotoToBytes(e.ChosenPhoto);
                    bmp.SetSource(e.ChosenPhoto);
                    image1.Source = bmp;
                }
                else if (photoSelected == 2)
                {
                    byteList[1] = ChosenPhotoToBytes(e.ChosenPhoto);
                    bmp.SetSource(e.ChosenPhoto);
                    image2.Source = bmp;
                }
                else
                {
                    byteList[2] = ChosenPhotoToBytes(e.ChosenPhoto);
                    bmp.SetSource(e.ChosenPhoto);
                    image3.Source = bmp;
                }

            }
        }

        private byte[] ChosenPhotoToBytes(Stream s)
        {
            //Convert the photo to bytes
            byte[] PhotoBytes = new byte[s.Length];

            // rewind first
            s.Position = 0;

            // now succeeds
            s.Read(PhotoBytes, 0, PhotoBytes.Length);

            return PhotoBytes;
        }
    }
}